package com.wanlian.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.wanlian.json.JsonStringUtil;

public class RequestUtil {

    protected static Logger logger = Logger.getLogger(RequestUtil.class);

    public static String getRequestPayload(HttpServletRequest request) {

        // StringBuilder sb = new StringBuilder();
        // BufferedReader reader = null;
        // char[] buff = new char[1024];
        // int len;
        //
        // try {
        // reader = req.getReader();
        // while((len = reader.read(buff)) != -1) {
        // sb.append(buff,0, len);
        // }
        // reader.close();
        // } catch (IOException e) {
        // logger.error("公共组件：以IO流获取客户端发送的Request数据时产生异常", e);
        // }
        //
        // return sb.toString();
        Map<String, Object> cmap = new HashMap<String, Object>();
        Map map = request.getParameterMap();
        Set keSet = map.entrySet();
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            Object ok = me.getKey();
            Object ov = me.getValue();
            String[] value = new String[1];
            if (ov instanceof String[]) {
                value = (String[]) ov;
                cmap.put(ok.toString(), value[0]);
            } else {
                // value[0] = ov.toString();
                cmap.put(ok.toString(), value);
            }

            // for (int k = 0; k < value.length; k++)
            // {
            // System.out.println(ok + "=" + value[k]);
            // }
        }
        return JsonStringUtil.writeValueAsString(cmap);
    }

    public static String getRemoteIPAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("Proxy-Client-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("WL-Proxy-Client-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getRemoteAddr();
        return ip;
    }

    public static void main(String args[]) {
        String str = "{\"OperType\":200,\"Param\":{\"MobileNumber\":\"13800138005\",\"CompanyId\":\"XXXX\",\"Password\":\"13800138005\",\"ValidationCode\":\"13800138005\"}}";

        JsonParser parser = new JsonParser();
        JsonObject object = (JsonObject) parser.parse(str);

        String operType = object.get("OperType").getAsString();

        System.out.println("operType = " + operType);

        try {
            JsonArray array = object.get("Param").getAsJsonArray(); // 得到为json的数组
            for (int i = 0; i < array.size(); i++) {
                JsonObject subObject = array.get(i).getAsJsonObject();

                System.out.println("id=" + subObject.get("id").getAsInt());
                System.out.println("text=" + subObject.get("text").getAsString());

                JsonArray arrayChildren = subObject.get("children").getAsJsonArray();
                for (int j = 0; j < array.size(); j++) {
                    System.out.println("---------------");
                    JsonObject subObject1 = arrayChildren.get(i).getAsJsonObject();

                    System.out.println("id=" + subObject1.get("id").getAsInt());
                    System.out.println("text=" + subObject1.get("text").getAsString());
                    System.out.println("leaf=" + subObject1.get("leaf").getAsString());
                }
            }
        } catch (JsonIOException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }
}
